<?php

namespace App\Jobs;

use App\Models\Bills;
use App\Models\StationBills;
use Illuminate\Bus\Queueable;
use Illuminate\Support\Facades\DB;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;

class CreateBill implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $service_id = '';
        $station_bills = [];
        $date = new \DateTime;
        $now_day = $date->modify('-1 day')->format('Y-m-d');
        $day = $date->modify('-1 day')->format('d');
        if($day < 16){
            $start_day = date('Y-m-01', strtotime(date("Y-m-d")));
        } else {
            $start_day = date('Y-m-16', strtotime(date("Y-m-d")));
        }

//        dd($start_day,$now_day);

        $bills = Bills::query()
            ->select
            (
                [
                    'date','service_id',
                    DB::raw('sum(total_sign) as sign'),
                    DB::raw('sum(total_income - (total_sign*0.1)) as income')
                ]
            )
            ->groupBy(['date','service_id'])
            ->whereBetween('date',[$start_day,$now_day])
            ->orderBy('service_id')
            ->get()
            ->toArray();

//        dd($bills);
        foreach ($bills as $bill){
            $station_bills[$bill['service_id']] = [];
            if($station_bills[$bill['service_id']] == $service_id){
                $station_bills[$service_id]['sign'] += $bill['sign'];
                $station_bills[$service_id]['income'] += $bill['income'];
            }else{
                $service_id = $bill['service_id'];
                $station_bills[$service_id]['sign'] = $bill['sign'];
                $station_bills[$service_id]['income'] = $bill['income'];
            }
        }
//        dd($station_bills);

        foreach ($station_bills as $id => $bill){
            dispatch(new CreateStationBill($start_day,$id,$now_day,$bill));
        }



    }
}
